package com.jack.nativeloadgif

import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.jack.nativeloadgif.databinding.ActivityMainBinding
import java.io.File

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    var bitmap: Bitmap? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        verifyStoragePermissions()
    }

    private fun verifyStoragePermissions() {
        val REQUEST_EXTERNAL_STORAGE = 1
        val PERMISSIONS_STORAGE = arrayOf(
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"
        )
        try {
            //检测是否有写的权限
            val permission = ActivityCompat.checkSelfPermission(
                this,
                "android.permission.WRITE_EXTERNAL_STORAGE"
            )
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private val myHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            val delay: Int = GifLoadHelper.getInstance().updateFrame(bitmap!!)
            this.sendEmptyMessageDelayed(1, delay.toLong())
            binding.image.setImageBitmap(bitmap)
        }
    }

    fun ndkLoadGif(view: View) {
        val file = File(Environment.getExternalStorageDirectory(), "demo.gif")

//        Toast.makeText(this, file.absolutePath, Toast.LENGTH_SHORT).show()
        ///storage/emulated/0/.
        //android的API的得到的就是/storage/emulated/0/，这个路径我们用的时候一般直接进/sdcard/或者/mnt/sdcard/，其实是一个相同的位置；
        //通过Device File Explorer查找到/mnt/sdcard的路径，并且将demo.gif文件拷贝进去；
        GifLoadHelper.getInstance().load(file.absolutePath)
        val width: Int = GifLoadHelper.getInstance().getWidth()
        val height: Int = GifLoadHelper.getInstance().getHeight()
        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        //通知C渲染完成
        val delay: Int = GifLoadHelper.getInstance().updateFrame(bitmap!!) //不健壮的点：c代码中需要开线程
        binding.image.setImageBitmap(bitmap)
        myHandler.sendEmptyMessageDelayed(1, delay.toLong())
    }
}